<template>
  <div class="medical-service-container">
    <div class="page-header">
      <h2>医嘱患者：夏洛兴</h2>
    </div>
    
    <div class="content-wrapper">
      <div class="section-header">
        <h3>医疗服务医嘱：</h3>
      </div>
      
      <div class="search-box">
        <el-input
          v-model="searchKeyword"
          placeholder="医疗服务"
          class="search-input"
        >
          <template #append>
            <el-button @click="handleSearch">
              搜索
            </el-button>
          </template>
        </el-input>
      </div>
      
      <el-table
        :data="filteredServiceList"
        stripe
        border
        style="width: 100%"
        highlight-current-row
        @row-click="handleRowClick"
      >
        <el-table-column type="index" label="序号" width="70" align="center" />
        <el-table-column prop="name" label="医疗服务中文名称" min-width="180" />
        <el-table-column prop="code" label="项目编码" width="160" />
        <el-table-column prop="nationalCode" label="国家编码" width="240" />
        <el-table-column prop="description" label="项目说明" min-width="180" />
        <el-table-column prop="exclusion" label="除外内容" min-width="180" />
        <el-table-column prop="unit" label="计价单位" width="100" align="center" />
        <el-table-column prop="price" label="价格" width="100" align="center" />
        <el-table-column label="增加医疗服务" width="120" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              plain
              @click.stop="handleAddService(scope.row)"
            >
              增加
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:currentPage="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalServices"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      
      <el-divider />
      
      <div class="selected-services">
        <h3>已选医疗服务：</h3>
        
        <el-table
          :data="selectedServices"
          stripe
          border
          style="width: 100%"
        >
          <el-table-column type="index" label="序号" width="70" align="center" />
          <el-table-column prop="name" label="医疗服务名称" min-width="180" />
          <el-table-column prop="code" label="项目编码" width="160" />
          <el-table-column prop="unit" label="计价单位" width="100" align="center" />
          <el-table-column prop="price" label="单价" width="100" align="center" />
          <el-table-column label="数量" width="120" align="center">
            <template #default="scope">
              <el-input-number 
                v-model="scope.row.quantity" 
                :min="1" 
                size="small"
                @change="handleQuantityChange"
              />
            </template>
          </el-table-column>
          <el-table-column prop="subtotal" label="金额" width="120" align="center" />
          <el-table-column label="操作" width="80" align="center">
            <template #default="scope">
              <el-button
                type="danger"
                size="small"
                plain
                @click.stop="handleRemoveService(scope.$index)"
              >
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="order-footer">
          <div class="total-amount">
            合计金额：<span>{{ totalAmount }}</span> 元
          </div>
          
          <div class="action-buttons">
            <el-button type="primary" @click="handleSaveOrder">保存医嘱</el-button>
            <el-button @click="handleCancel">取消</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';

const router = useRouter();
const route = useRoute();
const searchKeyword = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const selectedServices = ref([]);

// 模拟医疗服务数据
const serviceList = [
  {
    id: 1,
    code: '110200003-1c',
    name: '急诊诊查费(6岁及以下)(医师)',
    nationalCode: '00110200003000-110200003-1c',
    description: '',
    exclusion: '',
    unit: '次',
    price: 15
  },
  {
    id: 2,
    code: '110200003-2c',
    name: '急诊诊查费(6岁及以下)(主治医师)',
    nationalCode: '00110200003000-110200003-2c',
    description: '',
    exclusion: '',
    unit: '次',
    price: 20
  },
  {
    id: 3,
    code: '110200003-3c',
    name: '急诊诊查费(6岁及以下)(副主任医师及以上)',
    nationalCode: '00110200003000-110200003-3c',
    description: '',
    exclusion: '',
    unit: '次',
    price: 25
  },
  {
    id: 4,
    code: '110200004-1',
    name: '门/急诊留观诊查费(12小时以内)',
    nationalCode: '00110200004000-110200004-1',
    description: '',
    exclusion: '',
    unit: '日',
    price: 15
  },
  {
    id: 5,
    code: '110200004-1c',
    name: '门/急诊留观诊查费(12小时以内)(6岁及以下)',
    nationalCode: '00110200004000-110200004-1c',
    description: '',
    exclusion: '',
    unit: '日',
    price: 30
  },
  {
    id: 6,
    code: '110200004-2',
    name: '门/急诊留观诊查费(12小时以上)',
    nationalCode: '00110200004000-110200004-2',
    description: '',
    exclusion: '',
    unit: '日',
    price: 30
  },
  {
    id: 7,
    code: '110200004-2c',
    name: '门/急诊留观诊查费(12小时以上)(6岁及以下)',
    nationalCode: '00110200004000-110200004-2c',
    description: '',
    exclusion: '',
    unit: '日',
    price: 45
  },
  {
    id: 8,
    code: '110200005',
    name: '住院诊查费',
    nationalCode: '00110200005000-110200005',
    description: '',
    exclusion: '',
    unit: '日',
    price: 12
  },
  {
    id: 9,
    code: '110200005/1',
    name: '住院诊查费(甲类传染)',
    nationalCode: '00110200005000-110200005/1',
    description: '',
    exclusion: '',
    unit: '日',
    price: 15.6
  },
  {
    id: 10,
    code: '110200005/2',
    name: '住院诊查费(乙类传染)',
    nationalCode: '00110200005000-110200005/2',
    description: '',
    exclusion: '',
    unit: '日',
    price: 15.6
  }
];

// 总医疗服务数量
const totalServices = computed(() => {
  if (!searchKeyword.value) {
    return serviceList.length;
  }
  return serviceList.filter(service => 
    service.name.includes(searchKeyword.value) || 
    service.code.includes(searchKeyword.value)
  ).length;
});

// 过滤后的医疗服务列表
const filteredServiceList = computed(() => {
  if (!searchKeyword.value) {
    return serviceList.slice(
      (currentPage.value - 1) * pageSize.value,
      currentPage.value * pageSize.value
    );
  }
  
  const filtered = serviceList.filter(service => 
    service.name.includes(searchKeyword.value) || 
    service.code.includes(searchKeyword.value)
  );
  
  return filtered.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value
  );
});

// 计算总金额
const totalAmount = computed(() => {
  return selectedServices.value.reduce((sum, item) => sum + Number(item.subtotal), 0).toFixed(2);
});

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
};

// 处理表格行点击
const handleRowClick = (row) => {
  console.log('选中服务:', row);
};

// 处理添加医疗服务
const handleAddService = (service) => {
  // 检查是否已添加该项目
  const exists = selectedServices.value.some(item => item.id === service.id);
  if (exists) {
    // 如果已存在，增加数量
    const index = selectedServices.value.findIndex(item => item.id === service.id);
    selectedServices.value[index].quantity += 1;
    selectedServices.value[index].subtotal = (selectedServices.value[index].quantity * selectedServices.value[index].price).toFixed(2);
    ElMessage.success('已增加项目数量');
  } else {
    // 如果不存在，添加新项目
    const newItem = { 
      ...service, 
      quantity: 1,
      subtotal: service.price.toFixed(2)
    };
    selectedServices.value.push(newItem);
    ElMessage.success('已添加医疗服务');
  }
};

// 处理移除医疗服务
const handleRemoveService = (index) => {
  selectedServices.value.splice(index, 1);
  ElMessage.success('已移除医疗服务');
};

// 处理数量变化
const handleQuantityChange = () => {
  // 重新计算所有项目的金额
  selectedServices.value.forEach(item => {
    item.subtotal = (item.quantity * item.price).toFixed(2);
  });
};

// 处理保存医嘱
const handleSaveOrder = () => {
  if (selectedServices.value.length === 0) {
    ElMessage.warning('请至少添加一个医疗服务');
    return;
  }
  
  // 这里应该发送请求保存医嘱数据
  ElMessage.success('医疗服务医嘱保存成功');
  console.log('保存的医嘱:', selectedServices.value);
};

// 处理取消
const handleCancel = () => {
  ElMessageBox.confirm('确定取消医疗服务医嘱? 未保存的数据将丢失', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    router.go(-1);
  }).catch(() => {});
};

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
};

onMounted(() => {
  console.log('医疗服务医嘱组件已加载');
  // 这里可以获取患者ID和可能已有的医嘱
  const patientId = route.query.patientId;
  if (patientId) {
    console.log('患者ID:', patientId);
    // 获取患者信息和可能已有的医嘱
  }
});
</script>

<style scoped>
.medical-service-container {
  padding: 20px;
  height: 100%;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
  margin: 0;
}

.content-wrapper {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  min-height: calc(100% - 60px);
}

.section-header {
  margin-bottom: 20px;
}

.section-header h3 {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 0;
}

.search-box {
  margin-bottom: 20px;
  width: 400px;
}

.pagination-container {
  margin: 20px 0;
  display: flex;
  justify-content: flex-end;
}

.selected-services {
  margin-top: 20px;
}

.selected-services h3 {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 0 0 20px 0;
}

.order-footer {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-amount {
  font-size: 16px;
  font-weight: bold;
}

.total-amount span {
  color: #f56c6c;
  margin: 0 5px;
}

.action-buttons {
  text-align: right;
}

.el-divider {
  margin: 30px 0;
}
</style> 